import React from 'react';
import get from 'lodash/get';
import PropTypes from 'prop-types';
import { stripesConnect, IfPermission } from '@folio/stripes/core';

import { FormattedMessage, injectIntl } from 'react-intl';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import {

  Button,
  MultiColumnList
} from '@folio/stripes/components';
import { queryParamsCreate2 } from '../../util/QueryParamEdit';

import SearchForm from '../../components/party-notify-template/search-form';

class List extends React.Component {
  static manifest = Object.freeze({

    notifyTemplateQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    notifyTemplateRecords: {
      type: 'okapi',
      path: 'party/notify_template',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'limit',
      records: 'notifyTemplateGroup',
      GET: {
        params: {
          query: '( id <> 0 %{notifyTemplateQuery})'
        }
      }
      // offsetParam: 'pageNum'
    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      getDataList: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),

      notifyTemplateQuery: PropTypes.string,
      notifyTemplateRecords:PropTypes.shape({
        GET: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }),
    }).isRequired,

    history: PropTypes.object,
    toModel: PropTypes.func,
    intl:PropTypes.object,
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchFlag: true,
      searchForm: {}
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    // this.getDataList();
  }

  componentDidUpdate() {
    this.source.update(this.props);
  }

  componentWillUnmount() {
    const { mutator } = this.props;
    mutator.notifyTemplateQuery.replace('');
  }

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  deleteDate = id => {
    const { mutator, intl } = this.props;
    const msg = intl.formatMessage({
      id: 'ui-party.messageTemplate.confirm.del'
    });
    if (confirm(msg)) {

      mutator.notifyTemplateRecords.DELETE({ id }).then(() => {

      });
    }
  };

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    if (this.state.searchFlag) {
      mutator.notifyTemplateQuery.replace(queryParamsCreate2(formData));
      if (this.source) {
        this.source.update(this.props);
        this.setState(
          {
            searchForm: formData,
            searchFlag: false
          },
          () => {
            setTimeout(() => {
              this.setState({
                searchFlag: true
              });
            }, 500);
          }
        );
      }
    } else {
      console.log('防抖墙');
    }
  };

  cleanSearch = () => {
    const { mutator } = this.props;
    this.setState({
      searchForm: {
        name: ''
      }
    });
    mutator.notifyTemplateQuery.replace('');
    if (this.source) {
      this.source.update(this.props);
    }
  };

  toView = viewPath => {
    const { history } = this.props;
    history.push(viewPath);
  };

  openMessageTemplate = item => {
    const { mutator } = this.props;
    delete item.rowIndex;
    if (this.source) {
      item.state = 1;
      mutator.notifyTemplateRecords.PUT(item);
      this.source.update(this.props);
    }
  };

  render() {
    const { resources, toModel } = this.props;
    if (this.source) {
      this.source.update(this.props);
    }
    const dictionary = {
      notice:[
        { id: '', name: 'none', desc: 'ui-party.messageTemplate.data.notice.empty' },
        { id: 1, name: 'weixin', desc: 'ui-party.messageTemplate.data.notice.weixin' },
        { id: 2, name: 'sms', desc: 'ui-party.messageTemplate.data.notice.textMessage' },
        { id: 3, name: 'email', desc: 'ui-party.messageTemplate.data.notice.email' }
      ],
      type:[
        { id: '', name: 'none', desc: 'ui-party.messageTemplate.data.type.empty' },
        { id: 1, name: 'enrollSuccess', desc: 'ui-party.messageTemplate.data.type.enrollSuccess' },
        { id: 2, name: 'signInSuccess', desc: 'ui-party.messageTemplate.data.type.signInSuccess' },
        { id: 3, name: 'auditPass', desc: 'ui-party.messageTemplate.data.type.auditPass' },
        { id: 4, name: 'auditReject', desc: 'ui-party.messageTemplate.data.type.auditReject' }
      ],
      state:[

        { id: 1, name: 'enable', desc: 'ui-party.messageTemplate.data.state.enable' },
        { id: 0, name: 'disable', desc: 'ui-party.messageTemplate.data.state.disable' }
      ]
    };
    const totalCount = this.source ? this.source.totalCount() : 0;
    // const totalCount = get(resources, 'records.other.data.totalElements', 0);
    const dataList = get(resources, 'notifyTemplateRecords.records', []);
    const resultsFormatter = {
      name: item => `${item.name}`,
      notice: item => {
        const notice = (dictionary.notice || {}).find(
          t => t.id === item.notice
        );
        return (
          <FormattedMessage id={(notice || {}).desc || 'ui-party.empty'} />
        );
      },
      type: item => {
        const type = (dictionary.type || {}).find(t => t.id === item.type);
        return (
          <FormattedMessage id={(type || {}).desc || 'ui-party.empty'} />
        );
      },
      template: item => `${item.template}`,
      state: item => {
        if (item.state === 1) {
          return <div><FormattedMessage id={"ui-party.other.activated"}/></div>;
        } else {
          return <div><FormattedMessage id={"ui-party.other.unactivated"}/></div>;
        }
      },
      operation: item => {
        return (
          <div>
            {/* <Link to={editPath}></Link> */}
            <IfPermission perm="ui-party.notify.template.manage.view.edit">
              <Button
                onClick={() => {
                  toModel('/party/notify/template/edit', { id:item.id });
                }}
              >
                <FormattedMessage id="ui-party.loans.columns.operating.edit" />
              </Button>
            </IfPermission>
            <IfPermission perm="ui-party.notify.template.manage.view.modify">
              <Button
                onClick={() => {
                  this.openMessageTemplate(item);
                }}
              >
                {item.state === 1 ? <FormattedMessage id={"ui-party.messageTemplate.data.state.disable"}/> : <FormattedMessage id={"ui-party.messageTemplate.data.state.enable"}/>}
              </Button>
            </IfPermission>
            <IfPermission perm="ui-party.notify.template.manage.view.delete">
              <Button
                style={{ border: '1px solid #900', color: ' #900' }}
                onClick={() => {
                  this.deleteDate(item.id);
                }}
              >
                <FormattedMessage id="ui-party.loans.columns.operating.remove" />
              </Button>
            </IfPermission>
          </div>
        );
      }

    };
    return (
      <div>
        <SearchForm
          onSubmit={this.search}
          initialValues={this.state.searchForm}
          cleanSearch={this.cleanSearch}
          toModel={toModel}
          {...this.props}
        />

        <MultiColumnList
          height={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          // pagingType="click"
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          formatter={resultsFormatter}
          visibleColumns={[
            'name',
            'notice',
            'type',
            'template',
            'state',
            'operation'
          ]}
          columnMapping={{
            name: <FormattedMessage id="ui-party.messageTemplate.name" />,
            notice: (
              <FormattedMessage id="ui-party.messageTemplate.notice" />
            ),
            type: <FormattedMessage id="ui-party.messageTemplate.type" />,
            template: (
              <FormattedMessage id="ui-party.messageTemplate.template" />
            ),
            state: <FormattedMessage id="ui-party.messageTemplate.state" />,
            operation: <FormattedMessage id="ui-party.loans.columns.operating" />
          }}
          columnWidths={{
            name: '10%',
            notice: '10%',
            type: '12%',
            template: '38%',
            state: '10%',
            operation: '30%'
          }}
        />
      </div>
    );
  }
}
export default injectIntl(stripesConnect(List));
